function V = gen_iw(emat,priorV,priorT,flag_corr)
% =======================================================
% GENERATE INVERSE WISHART 
% function gen_iw(emat,priorV,priorT,flag_corr); 
%
% Prior is IW(priorV,priorT) 
% such that 
% j-th element follows IG2(priorV(j,j),priorT(j)-1) 
% priorV = S in Lubrano 
%
% NOTE: Sep 2008 changed from the (D,v) parametrization, where D=priorV*priorT: 
% to the (V,T) parametrization. 
% Hence if sig_m=a, sig_v=b delivers W degrees of freedom a and scale b, 
% let priorT=a, priorV=b s.t. 
% 
% If flag_corr==1 V will be non-diagonal 
% See test_gen_iw for an description 
% Alejandro Justiniano Sep 22 2008 
% =======================================================
if ~isempty(emat);
    [T n]=size(emat);
    Qone=emat'*emat;
else
    T=0;
    Qone=0;
    n=size(priorV,1); 
end
VH=Qone+priorV; 
if flag_corr==0
    VH=diag(diag(VH));
    shock=mvnrnd(zeros(n,1),eye(n)/VH,T+priorT);
    V=diag(1./diag((shock'*shock)));
else
    shock=mvnrnd(zeros(n,1),eye(n)/VH,T+priorT);
    V=eye(n)/(shock'*shock);
end 